﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dukou.BizService.Impl;
using Dukou.Caching;
using Dukou.Security.Dao;
using Dukou.Security.Domain;
using Spring.Transaction.Interceptor;

namespace Dukou.Security.BizService.Impl
{
    public class UserBizService : BaseBizService<IUserDao, User, Int64>, IUserBizService
    {
        /// <summary>
        /// 角色缓存
        /// </summary>
        private ICategoryCache<Int64, IList<string>> _rolesCache;

        public IRoleDao RoleDao { get; set; }

        public ICacheService CacheService 
        {
            set
            {
                //this._logonInfoCache = value.GetCategoryCache<Guid, LogonInfo>("logoninfo");
                this._rolesCache = value.GetCategoryCache<Int64, IList<string>>("__roles");
                //this._privilegesCache = value.GetCategoryCache<Guid, IList<string>>("privileges");
                //this._systemCompanyCache = value.GetCategoryCache<Guid, Company>("systemcompany");
            }
        }

        public User FindByName(string userName)
        {
            return this.EntityDao.FindByName(userName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="roleName"></param>
        [Transaction(ReadOnly = false)]
        public void GrantRole(User user, string roleName)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user", "用户为空.");
            }
            Role role = this.RoleDao.FindByName(roleName);
            if (role == null)
            {
                throw new ArgumentNullException("roleName", "未找到角色.");
            }
            IList<string> userRoles = this._rolesCache.Get(user.Id);
            if (userRoles != null && !userRoles.Contains(roleName))
            {
                userRoles.Add(roleName);
            }
            this.EntityDao.SaveOrUpdate(user);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public bool IsInRole(User user, string roleName)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user", "用户为空.");
            }
            IList<string> userRoles = this._rolesCache.Get(user.Id);
            if (userRoles != null && userRoles.Contains(roleName))
            {
                return true;
            }
            return user.Roles.Where(x => x.Name == roleName).Count() > 0;
        }
    }
}
